<?php

namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Log;

/**
 * 刷新机器运行时间
 */
class Machine extends Command
{

    /**
     * @var array $save_list 需要更新的设备
     */
    protected $save_list = [];

    protected function configure()
    {
        $this->setName('machine')->setDescription('更新机器状态');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->start();
    }

    protected function start()
    {
        try {
            $now_time = time();
            $list = $this->getDisableMachine($now_time);
            if (empty($list)) {
                Log::notice("没有需要运行的机器");
                return;
            }
            foreach ($list as $item) {

                $item->createtime = (int)$item->createtime;
                // 调整运行时间
                if ($now_time >= strtotime('0:0:0', $item->createtime) + 604800) {
                    $this->save_list [] = ['id' => $item->id, 'state' => '1', 'runtime' => $now_time];
                }
            }

            if (!empty($this->save_list)) {
                model('app\admin\model\Machine')->saveAll($this->save_list);
            }

        } catch (\Exception $e) {

            $data = [
                'err' => $e->getMessage() . ' ' . $e->getFile() . ' ' . $e->getLine(),
                'data' => $this->save_list,
            ];

            $tip = json_encode($data);
            Log::error("机器启动异常: $tip");
        }
    }

    /**
     * 获取停机中机器
     * @param int $expiration_time 到期时间
     * @return
     */
    protected function getDisableMachine($expiration_time)
    {
        return \app\admin\model\Machine::where(['state' => 0, 'expirationtime' => ['>', $expiration_time]])->field('id,specifications,state,createtime,user_id,expirationtime,activestate')->select();
    }
}